package com.lzz.bottomencapsulation.receiver;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;

import com.lzz.bottomencapsulation.consts.NetConsts;
import com.lzz.bottomencapsulation.entity.VersionEntity;
import com.lzz.bottomencapsulation.eventbus.MessageEvent;
import com.lzz.bottomencapsulation.utils.FileUtils;
import com.lzz.bottomencapsulation.utils.LUtils;
import com.lzz.bottomencapsulation.utils.SPUtils;

import org.greenrobot.eventbus.EventBus;

/***
 @package ${package}
 @filename ${APK下载完成广播接收}
 */
public class Download_APK_Receiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        LUtils.e("========================下载完成安装");

        long myDwonloadID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);

        VersionEntity versionEntity=SPUtils.getdownloadAPK();

        if (versionEntity==null) return;

        EventBus.getDefault().post(new MessageEvent(NetConsts.CODE_50001,versionEntity));

        if (versionEntity.getDwonloadID() == myDwonloadID) {

            String serviceString = Context.DOWNLOAD_SERVICE;

            DownloadManager dManager = (DownloadManager) context.getSystemService(serviceString);

            Uri uri=dManager.getUriForDownloadedFile(myDwonloadID);

            if (uri!=null){

                FileUtils.installApk(dManager.getUriForDownloadedFile(myDwonloadID), context);

            }

        }
    }

}
